var MixlyUrl = {};

MixlyUrl.BOARD_CONFIG = null;

/**
* @function url转json
* @description 输入url，返回json
* @param url {String} 输入的url字符串
* @return object
*/
MixlyUrl.urlToJson = function (url) {
    // 递归字符串生成json对象
    function strToObj(obj, str, value) {
        if(str.indexOf(".") !== -1) {
            let key = str.substring(0, str.indexOf("."));
            str = str.substring(str.indexOf(".") + 1, str.length);
            if (obj[key] === undefined) {
                obj[key] = {};
            }
            obj[key] = strToObj(obj[key], str, value);
            return obj;
        } else {
            obj[decodeURIComponent(str)] = decodeURIComponent(value);
            return obj;
        }
    }
    var hash;
    var myJson = {};
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        try {
            var hash0 = hash[0].replaceAll("@", "=");
            hash0 = hash0.replaceAll("$", "&");
            var hash1 = hash[1].replaceAll("@", "=");
            hash1 = hash1.replaceAll("$", "&");
            myJson = strToObj(myJson, hash0, hash1);
        } catch (e) {
            myJson = strToObj(myJson, hash[0], hash[1]);
        }
    }
    return myJson;
}

/**
* @function 获取板卡配置信息
* @description 返回当前板卡的配置信息
* @return object
*/
MixlyUrl.getBoardConfig = function () {
    var href = "";
    try {
        href = window.location.href.replaceAll("#", "");
    } catch (e) {
        //console.log(e);
        href = window.location.href;
    }
    href = href.substring(href.indexOf("?") + 1, href.length);
    var board_config = MixlyUrl.urlToJson(href);
    return board_config;
}

//json转url参数
MixlyUrl.jsonToUrl = function (param, key) {
    var paramStr = "";
    if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        try {
            var newKey = key.toString().replaceAll("=", "@");
            newKey = newKey.replaceAll("&", "$");
            var newParam = param.toString().replaceAll("=", "@")
            newParam = newParam.replaceAll("&", "$");
            paramStr += "&" + newKey + "=" + encodeURIComponent(newParam);
        } catch (e) {
            //console.log(e);
            paramStr += "&" + key + "=" + encodeURIComponent(param);
        }
    } else {
        $.each(param, function (i) {
            var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + MixlyUrl.jsonToUrl(this, k);
        });
    }
    return paramStr.substr(1);
};

MixlyUrl.changeURLArg = function (url, arg, argVal) {
    var pattern = arg + '=([^&]*)';
    var replaceText = arg + '=' + argVal;
    if (url.match(pattern)) {
        var tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
}

MixlyUrl.CRC32 = function (str, radix = 10) {
    const Utf8Encode = function (string) {
        string = string.replace(/\r\n/g, "\n");
        let text = "";
        for (let n = 0; n < string.length; n++) {
            const c = string.charCodeAt(n);
            if (c < 128) {
                text += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                text += String.fromCharCode((c >> 6) | 192);
                text += String.fromCharCode((c & 63) | 128);
            } else {
                text += String.fromCharCode((c >> 12) | 224);
                text += String.fromCharCode(((c >> 6) & 63) | 128);
                text += String.fromCharCode((c & 63) | 128);
            }
        }
        return text;
    }

    const makeCRCTable = function () {
        let c;
        const crcTable = [];
        for (let n = 0; n < 256; n++) {
            c = n;
            for (let k = 0; k < 8; k++) {
                c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
            }
            crcTable[n] = c;
        }
        return crcTable;
    }

    const crcTable = makeCRCTable();
    const strUTF8 = Utf8Encode(str);
    let crc = 0 ^ (-1);
    for (let i = 0; i < strUTF8.length; i++) {
        crc = (crc >>> 8) ^ crcTable[(crc ^ strUTF8.charCodeAt(i)) & 0xFF];
    }
    crc = (crc ^ (-1)) >>> 0;
    return crc.toString(radix);
};

MixlyUrl.initFingerprintJS = function () {
    // Initialize an agent at application startup.
    const fpPromise = FingerprintJS.load();

    // Get the visitor identifier when you need it.
    fpPromise
        .then(fp => fp.get())
        .then(result => {
            // This is the visitor identifier:
            let visitorId16 = result.visitorId;
            let VisitorIdNum = parseInt(visitorId16, 16);
            let visitorId32 = VisitorIdNum.toString(32);
            MixlyUrl.BOARD_CONFIG.visitorId = {
                str16: visitorId16,
                str32: visitorId32,
                str16CRC32b: MixlyUrl.CRC32(visitorId16, 16),
                str32CRC32b: MixlyUrl.CRC32(visitorId32, 16)
            };
            console.log(MixlyUrl.BOARD_CONFIG);
        })
        .catch(error => {
            console.error(error);
            console.log(MixlyUrl.BOARD_CONFIG);
        });
}

if (typeof (boardConfig) == "undefined") {
    if (nodeFs.existsSync(MixlyEnv.indexPath + "/config.json")) {
        let rawdata = nodeFs.readFileSync(MixlyEnv.indexPath + "/config.json");
        try {
            let boardUrl = MixlyUrl.getBoardConfig();
            MixlyUrl.BOARD_CONFIG = { ...JSON.parse(rawdata), ...boardUrl };
        } catch (e) {
            console.log(e);
        }
    }
} else {
    let boardUrl = MixlyUrl.getBoardConfig();
    MixlyUrl.BOARD_CONFIG = { ...boardConfig, ...boardUrl };
}

document.write(`<script async src="${MixlyUrl.BOARD_CONFIG?.thirdPartyBoard ? "../../" : "../"}common/modules/fp.min.js" type="text/javascript" onload="MixlyUrl.initFingerprintJS()"></script>`);

if (MixlyUrl.BOARD_CONFIG?.filePath && MixlyUrl.BOARD_CONFIG.filePath != "None") {
    let mixStr = nodeFs.readFileSync(MixlyUrl.BOARD_CONFIG.filePath, "utf8");
    if ('localStorage' in window && window['localStorage'] != null) {
        window.localStorage.setItem(MixlyUrl.BOARD_CONFIG.boardName, mixStr);
        window.localStorage.setItem(MixlyUrl.BOARD_CONFIG.boardName + ".filePath", MixlyUrl.BOARD_CONFIG.filePath);
    }
    history.replaceState({}, "", MixlyUrl.changeURLArg(window.location.href, "filePath", "None"));
}

if (!MixlyEnv.isClient && MixlyUrl.BOARD_CONFIG?.nav?.upload) {
    //如果是网页，则加载../common/Highcharts/目录下highcharts
    document.write('<script src="../common/modules/mixlyWeb/highcharts.js"></script>\n');
    //引入网页串口API
    document.write('<script src="../common/modules/mixlyWeb/web-serial-controller.js"></script>\n');
    document.write('<script src="../common/modules/mixlyWeb/web-serial.js"></script>\n');
    document.write('<script src="../common/modules/mixlyWeb/utilities.js"></script>\n');
    document.write('<script src="../common/modules/mixlyWeb/esptool.js"></script>\n');
    document.write('<script src="../common/modules/mixlyWeb/ampy.js"></script>\n');
    //引入网页烧录与上传API
    document.write('<script src="../common/modules/mixlyWeb/web-burn-upload.js"></script>\n');
}